package com.qf.filter;

import com.qf.util.JwtUtil;
import io.jsonwebtoken.Claims;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.http.HttpCookie;
import org.springframework.http.HttpStatus;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.util.MultiValueMap;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

/**
 * 鉴权过滤器
 * @author 千锋健哥
 */
@Component
public class AuthFilter implements GlobalFilter, Ordered {

    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        //1. 获取请求对象
        ServerHttpRequest request = exchange.getRequest();

        //2. 获取响应对象
        ServerHttpResponse response = exchange.getResponse();

        //3. 获取用户访问的uri路径
        String path = request.getURI().getPath();

        //4. 判断如果是登录路径, 注册路径, 退出路径放行
        if (path.contains("/auth/login")) {
            //放行当前请求
            return chain.filter(exchange);
        }

        //5. 从cookie中获取jwt令牌
        MultiValueMap<String, HttpCookie> cookies = request.getCookies();
        HttpCookie httpCookie = cookies.getFirst("token");

        //6. 判断如果jwt令牌不存在则, 抛出401权限不足异常
        if (httpCookie == null) {
            response.setStatusCode(HttpStatus.UNAUTHORIZED);
            return response.setComplete();
        }


        //7. 解析jwt令牌
        String jwt = httpCookie.getValue();



        try {
            //解析jwt
            Claims claims = JwtUtil.parseJWT(jwt);
            //将解析后的内容放入, 请求头中携带, 以便后续微服务在远程调用的时候,
            //可以携带权限到其他微服务中使用
            request.mutate().header("authorization", jwt);

            //8. 如果解析没问题, 那么请求放行
            return chain.filter(exchange);
        } catch (Exception e) {
            //9. 解析异常说明要么jwt超时,要么被人篡改伪造, 抛出401权限不足异常
            response.setStatusCode(HttpStatus.UNAUTHORIZED);
            return response.setComplete();
        }




    }

    @Override
    public int getOrder() {
        return 0;
    }

}
